<template>
  <component :is="mySlots[0]" />
  <button @click="sub">-</button>
  <!-- <h2 :style="$attrs.style">{{num}}</h2> -->
  <h2>{{num}}</h2>
  <button @click="add">+</button>
  <component :is="mySlots[1]" />
  <h3>Sum is: {{sum}}</h3>
  <button @click="userChange('罗洋洋学会了吗？')">{{user}}</button>
</template>

<script>
import {ref,watch,watchEffect,computed,inject} from "vue";
export default {
  props:{
    numInit:{type:Number,default:66},
  },
  emits:['change'],
  inheritAttrs:false, //自定义处理事件
  setup(props,context) {
    const {emit,expose,attrs,slots} = context
    const mySlots = slots.default();//默认插槽
    let num = ref(props.numInit);

    let user = inject('user')
    
    let userChange = inject('userChange')
    setTimeout(()=> user.value = '我变了...',1000)

    let add = ()=>{
      num.value++;
      emit('change',num.value);
    }
    let sub = ()=>{
      num.value--;
      emit('change',num.value);
    }
    // watch(num,()=>{
    //   num.value <= 0 ? num.value = 0  : ''
    // })
    /******watchEffect使用******/
    const stop = watchEffect(()=>{
      if(num.value < 0){ num.value = 0 };
      emit('change',num.value);
    })
    if(num.value == 0){stop()} /*watchEffect失效**/

    // 计算属性
    let sum = computed(()=> sum = num.value + 100)

    /*只暴露的东西*/
    expose({num,sum})
    /*****暴露给template*****/
    return {num,add,sub,attrs,mySlots,sum,user,userChange};
  },
  
}
</script>

<style>

</style>